/*
 * Copyright (C) 2011 Lavettacn Xiao (lavettacn@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lavettacn.android.app.sociallessness.fragment;

import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;

import com.lavettacn.android.app.sociallessness.R;
import com.lavettacn.android.app.sociallessness.account.AccountContentProvider;
import com.lavettacn.android.app.sociallessness.data.table.TableElement;
import com.lavettacn.android.app.sociallessness.util.Debug;


public class AccountListFragment extends BaseListFragment implements LoaderManager.LoaderCallbacks<Cursor>{

    private static final String TAG = "AccountListFragment";

    private SimpleCursorAdapter mAdapter;

    public static AccountListFragment newInstance() {
        AccountListFragment f = new AccountListFragment();
        return f;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setEmptyText(getActivity().getString(R.string.no_account_txt));
        mAdapter = new SimpleCursorAdapter(getActivity(),
                android.R.layout.simple_list_item_2, null,
                new String[] { TableElement.ACCOUNT_NAME,TableElement.SERVICE_TYPE },
                new int[] { android.R.id.text1, android.R.id.text2 }, 0);
        setListAdapter(mAdapter);
        getLoaderManager().initLoader(getLoaderId(), null, this);
    }

    public int getLoaderId() {
        return 0;
    }

    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        return new CursorLoader(getActivity(), AccountContentProvider.ACCOUNT_URI,
                null, null, null, null);
    }

    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
        Debug.logD(TAG, "onLoadFinished, cursor=" + cursor);
        mAdapter.swapCursor(cursor);
    }

    public void onLoaderReset(Loader<Cursor> cursor) {
        Debug.logD(TAG, "onLoaderReset, cursor=" + cursor);
        mAdapter.swapCursor(null);
    }
}
